package com.zis.util;

import java.security.MessageDigest;

/**
 * 
 * <b>说明：</b> MD5双重加密
 * 
 * @ClassName: MD5Salt
 * @author zhaohaitao(2543) 日期： 2015-7-24 上午11:56:36
 * 
 */
public class MD5Salt
{
    private String inStr;
    
    private MessageDigest md5;
    
    public MD5Salt(String inStr)
    {
        this.inStr = inStr;
        try
        {
            this.md5 = MessageDigest.getInstance("MD5");
        }
        catch (Exception e)
        {
            System.out.println(e.toString());
            e.printStackTrace();
        }
    }
    
    private String compute()
    {
        char[] charArray = this.inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++)
        {
            byteArray[i] = (byte)charArray[i];
        }
        byte[] md5Bytes = this.md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++)
        {
            int val = ((int)md5Bytes[i]) & 0xff;
            if (val < 16)
            {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
    
    /**
     * 用户登录时输入的密码与数据库加密密码进行比较
     * 
     * @param plaintextPwd 用户输入的明文密码
     * @param salt 随机“佐料” salt
     * @param md5Pwd 数据库中加密后的密码
     * @return
     */
    public static boolean compare(String plaintextPwd, String salt, String md5Pwd)
    {
        MD5Salt md5 = new MD5Salt(plaintextPwd);
        // 用MD5第一次加密
        String pwd = md5.compute();
        pwd = pwd + salt;
        // 再次用MD5加密
        MD5Salt m = new MD5Salt(pwd);
        // 得到最终密文
        String npwd = m.compute();
        return npwd.equals(md5Pwd);
    }
    
    /**
     * 密码盐 加密
     * 
     * @param plaintextPwd 明文密码
     * @param salt 用户名
     * @return
     */
    public static String enCode(String plaintextPwd, String salt)
    {
        MD5Salt md5 = new MD5Salt(plaintextPwd);
        // 用MD5第一次加密
        String pwd = md5.compute();
        pwd = pwd + salt;
        // 再次用MD5加密
        MD5Salt m = new MD5Salt(pwd);
        // 得到最终密文
        String npwd = m.compute();
        return npwd;
    }
    
    public static void main(String[] args)
    {
        MD5Salt md5 = new MD5Salt("admin");
        // 用MD5第一次加密
        String pwd = md5.compute();
        pwd = pwd + "0x1x1s0s1111s558";
        // 再次用MD5加密
        MD5Salt m = new MD5Salt(pwd);
        // 得到最终密文
        String npwd = m.compute();
        System.out.println(npwd);
    }
}
